<template>
  <div id="app">
    <router-view/>
    <el-amap v-if="!inwechat" style="display: none"
      ref="map"
      :vid="'amap-app'"
      :plugin="plugin"
      :amap-manager="amapManager"
      :zoom="zoom"
      :center="center">
      </el-amap>
  </div>
</template>
<script>
import { AMapManager } from 'vue-amap'
import { isWechat } from '@/libs/utils'
import wx from 'weixin-js-sdk'
import { API_REGEO } from '@/service/amap'
import { wxjsdkMixin } from '@/components/mixins'
import { API_WECHAT_SIGN } from '@/service/wechat'
import { PROJECT_URL } from '@/libs/config'
let mapInstance
export default {
  name: 'app',
  mixins: [wxjsdkMixin],
  data () {
    let that = this
    return {
      inwechat: isWechat(),
      zoom: 14,
      amapManager: new AMapManager(),
      mapInstance: undefined,
      center: [this.$store.state.user.lng, this.$store.state.user.lat], // 中心位置
      plugin: [
        {
          pName: 'Geolocation',
          showButton: false,
          buttonPosition: 'LT',
          showMarker: false,
          showCircle: false,
          markerOptions: {
            content: `<img src="${require('@/assets/images/map/locate.png')}" style="width:32px;height:32px"/>`
          },
          events: {
            init (o) {
              // that.$toast.loading({
              //   duration: 0,
              //   mask: false,
              //   message: '定位中'
              // })
              mapInstance = o
              let timeDiff = Math.round(new Date() / 1000) - that.$store.getters.getUserPosition.time
              if (timeDiff > 2 * 60 * 60) {
                that.reLocation()
              }
            },
            complete (result) {
              // console.log('全局定位', result)
              if (result.formattedAddress) that.$store.dispatch('saveGeoAddress', result.formattedAddress)
              if (result && result.position) {
                let lng = result.position.lng
                let lat = result.position.lat
                that.center = [lng, lat]
                that.$store.dispatch('saveUserPosition', { lng, lat, time: Math.round(new Date() / 1000) })
                that.$nextTick()
                // that.$toast('定位成功')
                // that.$toast.clear()
              } else {
                that.$toast.clear()
              }
            },
            error (result) {
              console.log(result)
              if (result.info === 'NOT_SUPPORTED') {
                that.$toat('浏览器不支持定位')
              } else {
                if (result.message === 'Geolocation permission denied.') {
                  that.$toast('没有定位权限，请刷新重试')
                } else {
                  that.$toast(result.message)
                }
              }
            }
          }
        }
      ]
    }
  },
  provide: function () {
    return {
      mapGetLocation: this.reLocation
    }
  },
  mounted () {
    if (isWechat()) {
      this.getWxConfig()
    }
    if (this.inwechat) {
      let timeDiff = Math.round(new Date() / 1000) - this.$store.getters.getUserPosition.time
      if (timeDiff > 2 * 60 * 60) {
        this.reLocation()
      }
    }
  },
  methods: {
    getWxConfig () {
      let url = PROJECT_URL
      // let url = window.location.href.split('#')[0]
      // console.log('签名地址', url)
      API_WECHAT_SIGN({
        requestUrl: encodeURIComponent(url)
      }).then(resData => {
        // console.log('wx',resData)
        this.wxInit(resData)
      })
    },
    wxInit (config) {
      wx.config({
        debug: false,
        appId: config.appid,
        timestamp: config.timestamp,
        nonceStr: config.noncestr,
        signature: config.signature,
        jsApiList: ['openLocation', 'getLocation', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'updateAppMessageShareData', 'updateTimelineShareData', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem']
      })

      wx.error(function (res) {
        console.error('wx err', res)
      })
    },
    reLocation () {
      this.$toast({
        position: 'bottom',
        message: '获取位置中'
      })
      console.log('定位', this.inwechat)
      if (this.inwechat) {
        this.getWxLocation(({ lng, lat }) => {
          // console.log(lng, lat)
          this.$store.dispatch('saveUserPosition', { lng, lat, time: Math.round(new Date() / 1000) })
          API_REGEO({ lng, lat }).then(resData => {
            console.log('amap address', resData)
            if (resData.status === 1) {
              this.$store.dispatch('saveGeoAddress', resData.regeocode.formatted_address)
            }
          })
        })
      } else {
        // console.log('locationinstance', mapInstance)
        mapInstance && mapInstance.getCurrentPosition()
      }
    }
  }
}
</script>

<style lang="less">
#app{
  height: 100%;
  -webkit-overflow-scrolling: touch;
  font-size: 14px;
}
</style>
